package server;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author MohamedNour
 */
public class MyServerSocket implements Runnable {

    private String address;
    private int port;
    private ServerSocket serverSocket;
    private Server server;

    public MyServerSocket(String address, int port, Server server) {
    	this.server = server;
        this.address = address;
        this.port = port;
    }

    @Override
	public void run() {
		// TODO Auto-generated method stub
    	try {
			openServer();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    
    public void openServer() throws IOException {
        serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            startWorking();

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            serverSocket.close();
        }
    }

    public void startWorking()
    {
        Socket clientSocket = null;
        while(true)
        {
            try {
                clientSocket = serverSocket.accept();
                final OutputStream serverOut = clientSocket.getOutputStream();
                final InputStream serverIn = clientSocket.getInputStream();
                new Thread(new Runnable() {
                    public void run() {
                        server.handleNewClient(serverOut, serverIn);
                    }
                }).start();
            } catch (IOException e) {
                System.err.println("Accept failed.");
            }

        }
    }
}
